package com.molyfun.parents.activity.report;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.molyfun.parents.R;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.rest.bean.ReportFromsTypeResponse;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.MPChartHelper;
import com.molyfun.parents.utils.StringUtils;
import com.molyfun.parents.view.MPChartMarkerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by Administrator on 2017/12/14 0014.
 */

public class TypeFragment extends BaseFragment {
    @InjectView(R.id.tv_strtime)
    TextView tv_time;
    @InjectView(R.id.barChart)
    BarChart barChart;

    private List<String> xAxisValues;
    private List<Float> yAxisValues1;
    private List<Float> yAxisValues2;
    private List<Float> yAxisValues3;
    private String mReportId;
    private int[] maxYValue;

    public static TypeFragment newInstance(int category, String strTime, String reportId, ArrayList<ReportFromsTypeResponse.ReportTypeBean.TypelistBean> typelist) {
        TypeFragment typeFragment = new TypeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("category", category);
        bundle.putString(Const.FLAG_TIME_INTERVAL, strTime);
        bundle.putString(Const.REPORT_ID, reportId);
        bundle.putParcelableArrayList("typlist", typelist);
        typeFragment.setArguments(bundle);
        return typeFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_report_type, null);
        ButterKnife.inject(this, view);
        initView();
        return view;
    }

    private void initView() {
        String timeInterval = getArguments().getString(Const.FLAG_TIME_INTERVAL);
        mReportId = getArguments().getString(Const.REPORT_ID);
        ArrayList<ReportFromsTypeResponse.ReportTypeBean.TypelistBean> typlist = getArguments().getParcelableArrayList("typlist");
        if (timeInterval != null && !TextUtils.isEmpty(timeInterval)) {
            tv_time.setText(timeInterval + "");
        }
        if (typlist != null && typlist.size() > 0) {
            initData(typlist);
            setThreeBarChart(barChart, maxValue(maxYValue), xAxisValues, yAxisValues1, yAxisValues2, yAxisValues3, "课程", "独立完成", "辅助完成");
        } else {
            return;
        }
    }

    private void initData(ArrayList<ReportFromsTypeResponse.ReportTypeBean.TypelistBean> typlist) {
        xAxisValues = new ArrayList<>();
        yAxisValues1 = new ArrayList<>();
        yAxisValues2 = new ArrayList<>();
        yAxisValues3 = new ArrayList<>();
        maxYValue = new int[typlist.size()];
        for (int i = 0; i < typlist.size(); i++) {
            maxYValue[i] = Integer.valueOf(typlist.get(i).getCoursetypetotal());
            ReportFromsTypeResponse.ReportTypeBean.TypelistBean bean = typlist.get(i);
            xAxisValues.add(bean.getTypename());
            yAxisValues1.add(StringUtils.convertToFloat(bean.getCoursetypetotal(), 0));
            yAxisValues2.add(StringUtils.convertToFloat(bean.getCoursetypefinishnum(), 0));
            yAxisValues3.add(StringUtils.convertToFloat(bean.getCoursetypeassistnum(), 0));
        }
    }

    private int maxValue(int[] ss) {
        int max = ss[0];
        for (int i = 0; i < ss.length; i++) {
            if (ss[i] > max) {
                max = ss[i];
            }
        }
        return max;
    }

    private void setThreeBarChart(BarChart barChart, int maxYvaluew, List<String> xAxisValue, List<Float> yAxisValue1, List<Float> yAxisValue2, List<Float> yAxisValue3, String bartilte1, String bartitle2, String bartitle3) {
        barChart.getDescription().setEnabled(false);//设置描述
        barChart.setPinchZoom(false);//设置不按比例放缩柱状图
        barChart.setExtraBottomOffset(10);
        barChart.setExtraTopOffset(30);

        MPChartMarkerView markerView = new MPChartMarkerView(barChart.getContext(), R.layout.custom_marker_view);
        barChart.setMarker(markerView);

        //x坐标轴设置
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(xAxisValue.size());
        xAxis.setCenterAxisLabels(true);
        xAxis.setDrawGridLines(false);

        xAxis.setValueFormatter(new MPChartHelper.MyXValueFormatter(xAxisValue));
        //y轴设置
        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setCenterAxisLabels(true);
        leftAxis.setDrawGridLines(false);
        leftAxis.setGridColor(Color.TRANSPARENT);
        leftAxis.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color_normal));
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(maxYvaluew + 1.2f);
        leftAxis.setLabelCount(maxYvaluew);
        leftAxis.setGridLineWidth(1f);
        leftAxis.setDrawAxisLine(true);//绘制y轴
        leftAxis.setEnabled(true);
//        leftAxis.setDrawLabels(true);
        leftAxis.setAxisMinValue(0.0f);//设置Y轴显示最小值，不然0下面会有空隙
        leftAxis.setValueFormatter(new MPChartHelper.MyYValueFormatter(maxYvaluew + 1));

        barChart.getAxisRight().setEnabled(false);
        barChart.getViewPortHandler().getMatrixTouch().postScale(2f,1f);
//        barChart.getXAxis().setLabelRotationAngle(-45);


        //图例设置
        Legend legend = barChart.getLegend();
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);

        //设置柱状图数据
        setThreeBarChartData(barChart, xAxisValue, yAxisValue1, yAxisValue2, yAxisValue3, bartilte1, bartitle2, bartitle3);

        barChart.animateX(1500);//数据显示动画，从左往右依次显示
        barChart.invalidate();
    }

    private void setThreeBarChartData(BarChart barChart, List<String> xAxisValue, List<Float> yAxisValue1, List<Float> yAxisValue2, List<Float> yAxisValue3, String bartilte1, String bartitle2, String bartitle3) {
        float groupSpace = 0.08f;
        float barSpace = 0.02f;
        float barWidth = 0.3f;
        // (0.3 + 0.02) * 3 + 0.04 = 1，即一个间隔为一组，包含三个柱图 -> interval per "group"

        ArrayList<BarEntry> first_entries = new ArrayList<>();
        ArrayList<BarEntry> second_entries = new ArrayList<>();
        ArrayList<BarEntry> third_entries = new ArrayList<>();

        for (int i = 0; i < xAxisValue.size(); i++) {

                first_entries.add(new BarEntry(i, yAxisValue1.get(i)));
                second_entries.add(new BarEntry(i, yAxisValue2.get(i)));
                third_entries.add(new BarEntry(i, yAxisValue3.get(i)));
        }
        first_entries.add(new BarEntry(xAxisValue.size(), -1));
        second_entries.add(new BarEntry(xAxisValue.size(), -1));
        third_entries.add(new BarEntry(xAxisValue.size(), -1));

        BarDataSet first_set, second_set, third_set;

        if (barChart.getData() != null && barChart.getData().getDataSetCount() > 0) {
            first_set = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            second_set = (BarDataSet) barChart.getData().getDataSetByIndex(1);
            third_set = (BarDataSet) barChart.getData().getDataSetByIndex(2);
            first_set.setValues(first_entries);
            second_set.setValues(second_entries);
            third_set.setValues(third_entries);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            first_set = new BarDataSet(first_entries, bartilte1);
            second_set = new BarDataSet(second_entries, bartitle2);
            third_set = new BarDataSet(third_entries, bartitle3);

            first_set.setColor(ContextCompat.getColor(barChart.getContext(), R.color.bar1course));
            second_set.setColor(ContextCompat.getColor(barChart.getContext(), R.color.bar2myself));
            third_set.setColor(ContextCompat.getColor(barChart.getContext(), R.color.bar3assisted));


            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(first_set);
            dataSets.add(second_set);
            dataSets.add(third_set);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);
            data.setHighlightEnabled(false);
            barChart.getLegend().setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);//设置注解的位置在左上方
//            barChart.getLegend().setForm(Legend.LegendForm.CIRCLE);//这是左边显示小图标的形状

            data.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int i, ViewPortHandler viewPortHandler) {
                    System.out.println("ValueFormatter" + value + "entry" + entry + i + "viewPortHandler" + viewPortHandler);
                    if (value > -1 && value - (int) value == 0f) {
                        return (int) value + "";
                    }
                    return "";
                }
            });
            barChart.setData(data);
        }

        barChart.getBarData().setBarWidth(barWidth);
        barChart.getAxisLeft().setAxisMinValue(0f);
        barChart.groupBars(0, groupSpace, barSpace);
    }
}
